<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- 修改后 -->
      <el-form-item label="老人姓名" prop="elderlyName">
        <el-input
          v-model="queryParams.elderlyName"
          placeholder="请输入老人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item
        label-width="120px"
        style="width: 400px"
        label="请假开始时间"
        prop="leaveStartTime"
      >
        <el-date-picker
          clearable
          v-model="queryParams.leaveStartTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择请假开始时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['le:request:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['le:request:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['le:request:remove']"
          >删除</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['le:request:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <!-- 新增：状态筛选按钮行 -->
    <el-row :gutter="10" class="mb-4">
      <el-button
        v-for="(item, index) in statusOptions"
        :key="index"
        :type="activeStatus === item.value ? 'primary' : 'default'"
        @click="handleStatusFilter(item.value)"
        style="margin-right: 8px"
      >
        {{ item.label }}
      </el-button>
      <!-- 新增：发起请假申请按钮 -->
      <el-col :span="2" style="margin-left: 15px">
        <el-button type="primary" icon="EditPen" @click="handleLeaveApplication"
          >发起请假申请</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="requestList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="老人姓名" align="center" prop="elderlyId">
        <template #default="scope">
          <span v-for="item in elderlyList" :key="item.id">
            <span v-if="item.id == scope.row.elderlyId">{{ item.name }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="老人身份证" align="center" prop="elderlyId">
        <template #default="scope">
          <span v-for="item in elderlyList" :key="item.id">
            <span v-if="item.id == scope.row.elderlyId">{{ item.idCard }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="请假开始时间"
        align="center"
        prop="leaveStartTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.leaveStartTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="预请假结束时间"
        align="center"
        prop="expectedEndTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.expectedEndTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="实际结束时间"
        align="center"
        prop="actualEndTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.actualEndTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="creator">
        <template #default="scope">
          <span v-for="item in userList" :key="item.userId">
            <span v-if="item.userId == scope.row.creator">{{
              item.nickName
            }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="穿键时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假状态" align="center">
        <!-- 不再依赖prop，改为自定义渲染 -->
        <template #default="scope">
          <el-tag
            :type="
              getLeaveStatus(scope.row) === '已返回'
                ? 'success' // 已返回：绿色
                : getLeaveStatus(scope.row) === '请假中'
                ? 'primary' // 请假中：蓝色
                : 'danger' // 超时未归/状态未知：红色
            "
          >
            {{ getLeaveStatus(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleReturn(scope.row)"
            v-hasPermi="['le:request:edit']"
            :disabled="getLeaveStatus(scope.row) === '已返回'"
            >返回</el-button
          >
          <el-button
            link
            type="primary"
            icon="View"
            @click="handleView(scope.row)"
            v-hasPermi="['le:request:query']"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改我的请假对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="requestRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="老人外键" prop="elderlyId">
          <el-input v-model="form.elderlyId" placeholder="请输入老人外键" />
        </el-form-item>
        <el-form-item label="请假开始时间" prop="leaveStartTime">
          <el-date-picker
            clearable
            v-model="form.leaveStartTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择请假开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预请假结束时间" prop="expectedEndTime">
          <el-date-picker
            clearable
            v-model="form.expectedEndTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择预请假结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实际结束时间" prop="actualEndTime">
          <el-date-picker
            clearable
            v-model="form.actualEndTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择实际结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实际请假天数" prop="actualLeaveDays">
          <el-input
            v-model="form.actualLeaveDays"
            placeholder="请输入实际请假天数"
          />
        </el-form-item>
        <el-form-item label="实际返回备注" prop="actualReturnRemark">
          <el-input
            v-model="form.actualReturnRemark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="创建人" prop="creator">
          <el-input v-model="form.creator" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="陪同人姓名" prop="companionName">
          <el-input
            v-model="form.companionName"
            placeholder="请输入陪同人姓名"
          />
        </el-form-item>
        <el-form-item label="陪同人电话" prop="companionPhone">
          <el-input
            v-model="form.companionPhone"
            placeholder="请输入陪同人电话"
          />
        </el-form-item>
        <el-form-item label="预请假天数" prop="expectedLeaveDays">
          <el-input
            v-model="form.expectedLeaveDays"
            placeholder="请输入预请假天数"
          />
        </el-form-item>
        <el-form-item label="请假理由" prop="leaveReason">
          <el-input
            v-model="form.leaveReason"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="业务ID" prop="businessId">
          <el-input v-model="form.businessId" placeholder="请输入业务ID" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增：填写返回时间弹窗（完全匹配文档1规则） -->
    <el-dialog
      title="填写返回时间"
      v-model="openReturnDialog"
      width="500px"
      append-to-body
    >
      <el-form
        ref="returnRef"
        :model="returnForm"
        :rules="returnRules"
        label-width="120px"
      >
        <!-- 实际返回时间：必填、默认当前时间、早于开始时间置灰 -->
        <el-form-item label="实际返回时间" prop="actualEndTime">
          <el-date-picker
            clearable
            v-model="returnForm.actualEndTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择实际返回时间"
            :default-value="new Date()"
            :disabled-date="
              (time) => disabledReturnTime(time, returnForm.leaveStartTime)
            "
            @change="calculateActualLeaveDays"
          >
          </el-date-picker>
        </el-form-item>
        <!-- 实际请假天数：自动计算、禁用手动输入 -->
        <el-form-item label="实际请假天数">
          <el-input
            v-model="returnForm.actualLeaveDays"
            placeholder="自动计算"
            disabled
          />
        </el-form-item>
        <!-- 备注：选填、限50字符 -->
        <!-- 备注：选填、限50字符 -->
        <el-form-item label="备注" prop="actualReturnRemark">
          <el-input
            v-model="returnForm.actualReturnRemark"
            type="textarea"
            placeholder="请输入内容"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <!-- 弹窗底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="openReturnDialog = false">取消</el-button>
          <el-button type="primary" @click="submitReturnForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Request">
import {
  listRequest,
  getRequest,
  delRequest,
  addRequest,
  updateRequest,
} from "@/api/le/request";
import { listElderly } from "@/api/le/elderly";
import { listUser } from "@/api/system/user";
import { useRouter } from "vue-router";
import { getElderlyByElderlyId } from "@/api/le/elderly";
import { getUser } from "@/api/system/user";
import { getAccraditationRecordByBussniessId } from "@/api/le/accraditationRecord";
import { ElMessage } from "element-plus";
const router = useRouter();
const { proxy } = getCurrentInstance();
// 新增：跳转到请假申请页面（使用菜单配置的路由地址）
function handleLeaveApplication() {
  // 路由地址为leaveApplication，直接跳转该路径（若依菜单路由通常无需带组件路径前缀）
  router.push({ path: "/xietong/shenqing/leaveApplication" });
}
const openReturnDialog = ref(false); // 返回弹窗开关
const returnRef = ref(null);

const requestList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    elderlyId: null,
    leaveStartTime: null,
    expectedEndTime: null,
    actualEndTime: null,
    actualLeaveDays: null,
    actualReturnRemark: null,
    creator: null,
    leaveStatus: null,
    companionType: null,
    companionName: null,
    companionPhone: null,
    expectedLeaveDays: null,
    leaveReason: null,
    businessId: null,
    elderlyName: null, // 新增：老人姓名模糊查询参数
  },
  rules: {
    elderlyId: [
      { required: true, message: "老人外键不能为空", trigger: "blur" },
    ],
    leaveStartTime: [
      { required: true, message: "请假开始时间不能为空", trigger: "blur" },
    ],
  },
});
const { queryParams, form, rules } = toRefs(data);
// 查看按钮操作
const handleView = async (row) => {
  try {
    // 1. 获取请假详情
    const leaveRes = await getRequest(row.id);
    console.log(leaveRes);
    if (leaveRes.code !== 200 || !leaveRes.data) {
      ElMessage.error("查询请假详情失败");
      return;
    }
    const leaveData = leaveRes.data;
    const businessId = leaveData.id; // 审批记录的businessId = 请假主键ID

    // 2. 获取老人信息
    let elderInfo = {};
    if (leaveData.elderlyId) {
      const elderRes = await getElderlyByElderlyId(leaveData.elderlyId);
      console.log(elderRes);
      if (elderRes.code === 200 && elderRes.data) {
        elderInfo = elderRes.data;
      }
    }

    // 3. 获取申请人信息
    let nurseNickName = "";
    if (leaveData.creator) {
      const nurseRes = await getUser(leaveData.creator);
      console.log(nurseRes);
      if (nurseRes.code === 200) {
        nurseNickName = nurseRes.data.nickName;
      }
    }
    // 4. 新增：通过businessId获取审批记录
    let accraditationRecord = {}; // 审批记录
    let approverName = "未知审批人"; // 提前声明审批人姓名变量，设置默认值
    if (businessId) {
      const accRes = await getAccraditationRecordByBussniessId(businessId);
      console.log(accRes);
      if (accRes.code === 200 && accRes.data) {
        accraditationRecord = accRes.data;
        console.log(accraditationRecord);
        approverName = accraditationRecord.approverName || "未知审批人";
      } else {
        ElMessage.warning("未查询到审批记录");
      }
    }

    // 新增：构建销假数据对象（从 leaveData 中提取）
    const leaveDetail = {
      actualEndTime: leaveData.actualEndTime || "", // 实际返回时间
      actualLeaveDays: leaveData.actualLeaveDays || "", // 实际请假天数
      actualReturnRemark: leaveData.actualReturnRemark || "", // 销假备注
      leaveStatus: getLeaveStatus(row), // 传递请假状态（判断是否“已返回”）
    };
    // 4. 构建 basicForm
    const basicForm = {
      elderlyId: leaveData.elderlyId || "",
      elderName: elderInfo.elderlyName || "未知老人",
      idCard: elderInfo.elderlyIdCard || "无",
      phone: elderInfo.elderlyPhone || "无",
      nursingLevel: elderInfo.nursingLevel || "无",
      bed:
        `${elderInfo.floorName || ""}楼${elderInfo.roomNo || ""}房间${
          elderInfo.bedNo || ""
        }床位` || "无",
      nurse: elderInfo.caregiverName || "无",
    };

    // 5. 构建 applyForm
    const applyForm = {
      accompanyType: leaveData.companionType || "无",
      accompanyName:
        leaveData.companionName === "0"
          ? "无"
          : leaveData.companionName || "无",
      accompanyPhone:
        leaveData.companionPhone === "0"
          ? "无"
          : leaveData.companionPhone || "无",
      leavePeriod: [leaveData.leaveStartTime, leaveData.expectedEndTime],
      leaveDays: leaveData.expectedLeaveDays || 0,
      leaveReason: leaveData.leaveReason || "无",
    };

    // 6. 构建 submitData
    const submitData = {
      elderlyId: leaveData.elderlyId || "",
      businessId: leaveData.businessId, // 传递businessId
      nurseNickName: nurseNickName,
      createTime: leaveData.createTime || formatTime(new Date()),
      leaveStartTime: leaveData.leaveStartTime || "",
      expectedEndTime: leaveData.expectedEndTime || "",
    };
    const billNo = leaveData.businessId; // 单据编号

    // 7. 跳转到 index2.vue
    router.push({
      path: "/leaveApplication/applicantDetail",
      query: {
        leaveId: leaveData.id, // 请假主键ID（用于定位请假记录）
        billNo: billNo, // 已修改为仅用 leaveData.businessId
        basicForm: JSON.stringify(basicForm),
        applyForm: JSON.stringify(applyForm),
        submitData: JSON.stringify(submitData),
        accraditationRecord: JSON.stringify(accraditationRecord),
        approverName: approverName,
        leaveDetail: JSON.stringify(leaveDetail), // 新增：传递销假数据
      },
    });
  } catch (error) {
    console.error("查看请假详情失败:", error);
    ElMessage.error("查看请假详情失败，请重试");
  }
};
//获取用户信息列表
const userList = ref([]);
const getUserList = () => {
  listUser({ pageNum: 1, pageSize: 9999 }).then((response) => {
    console.log(response);
    userList.value = response.rows;
  });
};
//获取老人信息列表
const elderlyList = ref([]);
const getElderlyList = () => {
  listElderly({ pageNum: 1, pageSize: 9999 }).then((response) => {
    elderlyList.value = response.rows;
  });
};
// 新增：判断请假状态的方法
const getLeaveStatus = (row) => {
  // 1. 已填写实际返回时间 → 已返回
  if (row.actualEndTime && row.actualEndTime.trim() !== "") {
    return "已返回";
  }
  // 2. 无实际返回时间，对比当前时间与预计返回时间
  if (row.expectedEndTime && row.expectedEndTime.trim() !== "") {
    const currentTime = new Date(); // 当前时间
    const expectedTime = new Date(row.expectedEndTime); // 预计返回时间
    // 当前时间 ≤ 预计返回时间 → 请假中；否则 → 超时未归
    return currentTime <= expectedTime ? "请假中" : "超时未归";
  }
  // 3. 无预计返回时间（异常情况）→ 状态未知
  return "状态未知";
};

/** 查询我的请假列表 */
function getList() {
  loading.value = true;
  // 处理老人姓名参数：空字符串转为null，适配后端查询逻辑
  const requestParams = { ...queryParams.value };
  if (requestParams.elderlyName?.trim() === "") {
    requestParams.elderlyName = null;
  }
  listRequest(requestParams)
    .then((response) => {
      requestList.value = response.rows;
      total.value = response.total;
      loading.value = false;
      // 新增调试：打印后端返回的数据，确认是否有值
      console.log("后端返回的超时未归数据：", response.rows);
    })
    .catch(() => {
      loading.value = false; // 请求失败时也关闭加载状态
    });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    elderlyId: null,
    leaveStartTime: null,
    expectedEndTime: null,
    actualEndTime: null,
    actualLeaveDays: null,
    actualReturnRemark: null,
    createTime: null,
    creator: null,
    leaveStatus: null,
    companionType: null,
    companionName: null,
    companionPhone: null,
    expectedLeaveDays: null,
    leaveReason: null,
    businessId: null,
    extraField1: null,
    extraField2: null,
  };
  proxy.resetForm("requestRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  activeStatus.value = null;
  queryParams.value.leaveStatus = null;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加我的请假";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getRequest(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改我的请假";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["requestRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateRequest(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRequest(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除我的请假编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delRequest(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "le/request/export",
    {
      ...queryParams.value,
    },
    `request_${new Date().getTime()}.xlsx`
  );
}
// 返回弹窗表单：含请假开始时间（用于计算）、实际返回时间（后端字段）、天数、备注
const returnForm = reactive({
  id: null, // 请假记录ID（用于更新）
  leaveStartTime: null, // 请假开始时间（用于计算天数和禁用时间）
  actualEndTime: null, // 后端实体类字段（文档2：actualEndTime）
  actualLeaveDays: null, // 实际请假天数
  actualReturnRemark: "", // 备注
});
// 返回弹窗验证规则（匹配文档1）
const returnRules = reactive({
  actualEndTime: [
    { required: true, message: "请选择实际返回时间", trigger: "blur" }, // 必填提示
  ],
});
// 原方法不变，新增返回弹窗相关方法
/** 1. 打开返回弹窗：传入当前请假行数据 */
const handleReturn = (row) => {
  // 重置表单
  returnForm.id = row.id; // 携带请假记录ID
  returnForm.leaveStartTime = row.leaveStartTime; // 传入请假开始时间
  returnForm.actualEndTime = null;
  returnForm.actualLeaveDays = null;
  returnForm.actualReturnRemark = "";
  // 打开弹窗
  openReturnDialog.value = true;
};
/** 2. 禁用早于请假开始时间的选择（文档1规则） */
const disabledReturnTime = (time, leaveStartTime) => {
  if (!leaveStartTime) return false;
  // 请假开始时间转时间戳
  const leaveStartTimestamp = new Date(leaveStartTime).getTime();
  // 选择的时间（精确到分钟）早于请假开始时间则禁用
  return time.getTime() < leaveStartTimestamp - 1000 * 60;
};
/** 3. 自动计算实际请假天数（修正后：符合规则+数字类型） */
const calculateActualLeaveDays = () => {
  if (!returnForm.leaveStartTime || !returnForm.actualEndTime) return;

  // 1. 精确计算时间差（毫秒转天数，保留原始精度）
  const start = new Date(returnForm.leaveStartTime).getTime();
  const end = new Date(returnForm.actualEndTime).getTime();
  const diffMs = end - start;
  const diffDays = diffMs / (24 * 60 * 60 * 1000);

  // 2. 拆分整数和小数部分，按规则计算实际天数
  const integerPart = Math.floor(diffDays);
  const decimalPart = diffDays - integerPart;

  let actualDays;
  if (diffDays < 0.5) {
    actualDays = 0.5; // ＜0.5天 → 0.5
  } else if (diffDays > 0.5 && diffDays < 1) {
    actualDays = 1.0; // 0.5＜天数＜1 → 1
  } else {
    // ≥1天的情况：小数部分＜0.5则加0.5，否则加1.0
    actualDays = decimalPart < 0.5 ? integerPart + 0.5 : integerPart + 1.0;
  }

  // 3. 赋值为数字类型
  returnForm.actualLeaveDays = actualDays;
};

/** 4. 提交返回表单：调用updateRequest更新数据 */
const submitReturnForm = () => {
  proxy.$refs["returnRef"].validate((valid) => {
    if (valid) {
      // 构造更新参数：仅传需要更新的字段（ID、实际返回时间、天数、备注）
      const updateParams = {
        id: returnForm.id,
        actualEndTime: returnForm.actualEndTime, // 后端字段（文档2）
        actualLeaveDays: returnForm.actualLeaveDays,
        actualReturnRemark: returnForm.actualReturnRemark,
        leaveStatus: "已返回", // 关键新增：传递请假状态给后端，同步更新数据库
      };
      // 调用updateRequest接口
      updateRequest(updateParams).then((response) => {
        proxy.$modal.msgSuccess("返回时间提交成功");
        openReturnDialog.value = false; // 关闭弹窗
        getList(); // 刷新列表：状态会自动变为“已返回”（原getLeaveStatus方法生效）
      });
    }
  });
};
// 新增：状态筛选配置
const statusOptions = ref([
  { label: "全部", value: null },
  { label: "请假中", value: "请假中" },
  { label: "超时未归", value: "超时未归" },
  { label: "已返回", value: "已返回" },
]);
const activeStatus = ref(null); // 当前选中的状态
// 新增：状态筛选点击事件
const handleStatusFilter = (status) => {
  activeStatus.value = status;
  queryParams.value.leaveStatus = status; // 设置状态筛选参数
  handleQuery(); // 触发列表查询
};
// 日期格式化函数
const formatTime = (time) => {
  if (!time) return "";
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hour = String(date.getHours()).padStart(2, "0");
  const minute = String(date.getMinutes()).padStart(2, "0");
  const second = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
};
getElderlyList();
getUserList();
getList();
</script>
